from rest_framework import serializers
from .models import User
import re
from django_redis import get_redis_connection
import logging
from rest_framework_jwt.settings import api_settings
logger = logging.getLogger('django')
class CreateUserSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(label='密码', write_only=True)
    sms_code = serializers.CharField(label='验证码', write_only=True)
    allow = serializers.CharField(label='同意协议', write_only=True)
    token = serializers.CharField(label='登录状态token', read_only=True)  # 增加token字段
    class Meta:

        model = User
        # fields = ['id', 'username', 'password', 'password2', 'sms_code', 'mobile']
        fields = ['id', 'username', 'password', 'password2', 'sms_code', 'mobile', 'allow', 'token']
        extra_kwargs = {
            'username': {
                'max_length': 20,
                'min_length': 5,
                'error_messages':{
                    'max_length': '仅允许5-20个字符的用户名',
                    'min_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'max_length': 20,
                'min_length': 5,
                'error_messages': {
                    'max_length': '仅允许8-20个字符的密码',
                    'min_length': '仅允许8-20个字符的密码',
                }

            }
        }
    # 验证手机号
    def validate_mobile(self, value):
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号不符合规则')
        return value
    # 验证是否通过协议
    def validata_allow(self, value):
        if value != 'true':
            raise serializers.ValidationError('需要同意协议')
        return value
    # 验证两次密码一致性, 验证短信验证码
    def validata(self, data):

        password = data['password']
        password2 = data['password2']
        mobile = data['mobile']
        sms_code = data['sms_code']

        if password != password2:
            raise serializers.ValidationError('密码不一致')
        redis_conn = get_redis_connection('verify_code')
        real_sms = redis_conn.get('sms_%s' % mobile)
        if not real_sms:
            raise serializers.ValidationError('验证码已经过期')
        try:
            redis_conn.delete('sms_%s' % mobile)
        except Exception as e:
            logger.error(e)
        if real_sms.decode() != sms_code:
            raise serializers.ValidationError('验证代码错误')
        return data

    # 创建用户
    def create(self, validated_data):

        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']
        user = super().create(validated_data)
        user.set_password(validated_data['password'])
        user.save()
        # 使用jwt实现状态保持生成token
        jwt_playload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        playload = jwt_playload_handler(user)
        token = jwt_encode_handler(playload)
        user.token = token
        return user


